package model;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import enums.Symbols;

public class AttributesList {
	
	private static Pattern attributePattern = Pattern.compile("((\\w+):)?(\\w+)=\"(.*)\"");
	
	private ArrayList<Attribute> source;

	public AttributesList(String chunk) {
		this.source = parse(chunk);
	}
	
	private ArrayList<Attribute> parse(String chunk) {
		ArrayList<Attribute> result = new ArrayList<Attribute>(); 
		int index = chunk.indexOf(Symbols.SPACE.getValue());
		if (index != -1)
		{
			chunk = chunk.substring(index + 1, chunk.length());
			String[] parts = chunk.split(Symbols.SPACE.getValue());
			for (String part : parts) {
				Matcher matcher = attributePattern.matcher(part);
				if (matcher.find()) {
					Attribute attribute = new Attribute();
					attribute.setNamespace(matcher.group(2));
					attribute.setName(matcher.group(3));
					attribute.setValue(matcher.group(4));
					result.add(attribute);
				}
			}
		}		
		return result;
	}

	@Override
	public String toString() {
		return StringUtils.join(source.toArray(), Symbols.SPACE.getValue() );
	}


	
	

}
